package org.sixtynine.stock.controller;

import java.util.Date;

import javax.servlet.http.HttpServletRequest;

import org.sixtynine.stock.ReturnData;
import org.sixtynine.stock.dto.GridPramDTO;
import org.sixtynine.stock.dto.Page;
import org.sixtynine.stock.entity.Banner;
import org.sixtynine.stock.entity.BaseEntity;
import org.sixtynine.stock.entity.User;
import org.sixtynine.stock.model.FileUploadForm;
import org.sixtynine.stock.model.LoadingSearchCriteria;
import org.sixtynine.stock.service.BannerService;
import org.sixtynine.stock.service.GenericService;
import org.sixtynine.stock.service.content.DataManagerService;
import org.sixtynine.stock.service.file.FileDataService;
import org.sixtynine.stock.service.file.FileDataServiceImpl;
import org.sixtynine.stock.util.FileUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

/**
 * @author Thilan this class handle daily share data
 */

@Controller
@SessionAttributes
public class BannerUploadController extends BackEndAuthController {

	/** TODO configure */
	private int RECORDS_PER_PAGE = 10;

	@Autowired
	private GenericService genericService;

	@Autowired
	private BannerService bannerService;

	@Autowired
	private FileDataService fileDataService;

	@Autowired
	DataManagerService dataManagerService;

	@RequestMapping(value = "/admin/bannerupload/search")
	public ModelAndView search(@ModelAttribute LoadingSearchCriteria criteria) {
		ModelAndView modelAndView = new ModelAndView("/admin/bannerupload/list");
		loadData(1, -1, criteria.getFromDate(), criteria.getToDate(),
				modelAndView, criteria);

		return modelAndView;
	}

	@RequestMapping(value = "/admin/bannerupload/add")
	public ModelAndView addBanner(HttpServletRequest request) {
		ModelAndView modelAndView = null;

		if (!isUserLogged(request)) {
			modelAndView = new ModelAndView("/login/login");
			return modelAndView;
		}

		modelAndView = new ModelAndView("/admin/bannerupload/add");
		modelAndView.addObject("banner", new Banner());
		modelAndView.addObject("userLogged", true);

		return modelAndView;
	}

	@RequestMapping(value = "/admin/bannerupload/add/process")
	public ModelAndView addingBanner(
			@ModelAttribute("uploadFile") FileUploadForm uploadFile,
			@RequestParam("startDate") Date startDate, BindingResult result,
			@RequestParam("endDate") Date endDate,
			@RequestParam("bannerName") String fileName,
			@RequestParam("positionCode") String positionCode,
			@RequestParam("link") String link, HttpServletRequest request) {

		ModelAndView modelAndView = null;

		if (!isUserLogged(request)) {
			// TODO add error message
			modelAndView = new ModelAndView("/login/login");
			modelAndView.addObject("registedUser", new User());
			return modelAndView;
		}

		MultipartFile multipartFile = uploadFile.getFile();
		String orinalFileName = multipartFile.getOriginalFilename();
		String extention = FileUtil.getFileExtention(orinalFileName);

		String uploadFileName = fileName + "." + extention;

		ReturnData<String> returnData = fileDataService.saveFile(multipartFile,
				FileDataServiceImpl.COMPANY_DOCUMENT, uploadFileName);

		StringBuilder message = new StringBuilder();
		if (returnData._isSuccess()) {

			Banner banner = new Banner();
			banner.setBannerName(uploadFileName);
			banner.setEndDate(endDate);
			banner.setLink(link);
			banner.setPositionCode(positionCode);
			banner.setStartDate(startDate);

			genericService.saveOrUpdate(banner);
			modelAndView = new ModelAndView("/admin/bannerupload/list");

			loadData(1, -1, null, null, modelAndView, null);
		} else {
			modelAndView = new ModelAndView("/admin/bannerupload/add");
			message.append(uploadFileName);
		}

		modelAndView.addObject("message", message);

		return modelAndView;
	}

	@RequestMapping(value = "/admin/bannerupload/list")
	public ModelAndView listOfCompanyDocument(
			HttpServletRequest request,
			@RequestParam(value = "page", required = false) Integer page,
			@RequestParam(value = "totalRecords", required = false) Integer totalRecords) {

		ModelAndView modelAndView = null;

		if (!isUserLogged(request)) {
			modelAndView = new ModelAndView("/login/login");
			return modelAndView;
		}
		modelAndView = new ModelAndView("/admin/bannerupload/list");
		loadData(page, totalRecords, null, null, modelAndView, null);

		modelAndView.addObject("userLogged", true);

		return modelAndView;
	}

	/**
	 * load data
	 * 
	 * @param page
	 * @param totalRecords
	 * @param companyId
	 * @param fromDate
	 * @param toDate
	 * @param modelAndView
	 */
	private void loadData(Integer page, Integer totalRecords, Date fromDate,
			Date toDate, ModelAndView modelAndView,
			LoadingSearchCriteria criteria) {
		GridPramDTO gridPramDTO = new GridPramDTO();
		gridPramDTO.setRows(RECORDS_PER_PAGE);
		if (page != null) {
			gridPramDTO.setPage(page);
		} else {
			gridPramDTO.setPage(1);
		}
		if (totalRecords != null) {
			gridPramDTO._setTotalNumberOfRecords(totalRecords);
		}
		Page<Banner> bannerPage = bannerService.searchBanner(fromDate, toDate,
				gridPramDTO);
		modelAndView.addObject("bannerPage", bannerPage);
		if (criteria == null) {
			criteria = new LoadingSearchCriteria();
			criteria.setFromDate(fromDate);
			criteria.setToDate(toDate);
		}
		modelAndView.addObject("criteria", criteria);

	}

	@RequestMapping(value = "/admin/bannerupload/edit/{id}", method = RequestMethod.GET)
	public ModelAndView editBanner(HttpServletRequest request,
			@PathVariable Integer id) {
		ModelAndView modelAndView = null;
		if (!isUserLogged(request)) {
			modelAndView = new ModelAndView("/login/login");
			return modelAndView;
		}
		modelAndView = new ModelAndView("/admin/bannerupload/edit");
		BaseEntity banner = genericService.findById(id, Banner.class);
		modelAndView.addObject("banner", banner);
		modelAndView.addObject("userLogged", true);

		return modelAndView;
	}

	@RequestMapping(value = "/admin/bannerupload/edit/{id}", method = RequestMethod.POST)
	public ModelAndView edditingBanner(@ModelAttribute Banner banner,
			@PathVariable Integer id) {

		genericService.saveOrUpdate(banner);
		ModelAndView modelAndView = new ModelAndView("/admin/bannerupload/list");

		String message = "Record successfully updated.";
		modelAndView.addObject("message", message);
		loadData(1, -1, banner.getStartDate(), banner.getEndDate(),
				modelAndView, null);

		return modelAndView;
	}

	@RequestMapping(value = "/admin/bannerupload/delete/{id}", method = RequestMethod.GET)
	public ModelAndView deleteBanner(@PathVariable Integer id) {

		genericService.delete(id, Banner.class);
		ModelAndView modelAndView = new ModelAndView("/admin/bannerupload/list");
		String message = "Record successfully deleted.";
		modelAndView.addObject("message", message);
		loadData(1, -1, null, null, modelAndView, null);
		return modelAndView;
	}

}
